package com.huijie.core.interceptor;

import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.Set;

/**
 * @ClassName GlobalExceptionHandler
 * @Description 全局异常handle
 * @Author zyc
 * @Date 2019/1/3 14:44
 * @Version 1.0
 */
@ControllerAdvice
@Component
public class GlobalExceptionHandler {

    /**
     * @return org.springframework.validation.beanvalidation.MethodValidationPostProcessor
     * @description: 方法内参数校验器
     * @author zyc
     * @date 2019/1/3 14:19
     */
    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        return new MethodValidationPostProcessor();
    }

    /**
     * 捕获校验异常
     * @param exception
     * @return
     */
    @ExceptionHandler(ValidationException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String handle(ValidationException exception) {
        String msg = "";
        if (exception instanceof ConstraintViolationException) {
            ConstraintViolationException exs = (ConstraintViolationException) exception;

            Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
            for (ConstraintViolation<?> item : violations) {
                //打印验证不通过的信息
                msg += ","+item.getMessage();
            }
        }
        return "bad request"+msg;
    }
}